const express = require('express');
const router = express.Router();
const User = require('../models/user');

// 用户管理页面
router.get('/', (req, res) => {
    User.getAll((err, users) => {
        if (err) return res.status(500).send('Error retrieving users');
        res.render('userManagement', { users });
    });
});

// 添加用户页面
router.get('/add', (req, res) => {
    res.render('addUser');
});

// 处理添加用户请求
router.post('/add', (req, res) => {
    const { username, password, email } = req.body;
    User.create(username, password, email, (err) => {
        if (err) return res.status(500).send('Error adding user');
        res.redirect('/users');
    });
});

// 删除用户
router.get('/delete/:id', (req, res) => {
    const { id } = req.params;
    User.deleteById(id, (err) => {
        if (err) return res.status(500).send('Error deleting user');
        res.redirect('/users');
    });
});

// 修改用户页面
router.get('/edit/:id', (req, res) => {
    const { id } = req.params;
    User.findById(id, (err, user) => {
        if (err) return res.status(500).send('Error retrieving user');
        res.render('editUser', { user });
    });
});

// 处理修改用户请求
router.post('/edit/:id', (req, res) => {
    const { id } = req.params;
    const { username, email } = req.body;
    User.updateById(id, { username, email }, (err) => {
        if (err) return res.status(500).send('Error updating user');
        res.redirect('/users');
    });
});

module.exports = router;